/**********
    @name: 生成随机数 getRandomString
    @describtion: len: 长度
    @author:liubingye
    @date:2022-12-07 15:59:10
***********/
const _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789';

function RandomIndex(min, max, i){
    let index = Math.floor(Math.random()*(max-min+1)+min),
        numStart = _charStr.length - 10;
    //如果字符串第一位是数字，则递归重新获取
    if(i==0&&index>=numStart){
        index = RandomIndex(min, max, i);
    }
    //返回最终索引值
    return index;
}
export function getRandomString(len){
    let min = 0, max = _charStr.length-1, _str = '';
    //判断是否指定长度，否则默认长度为15
    len = len || 15;
    //循环生成字符串
    for(var i = 0, index; i < len; i++){
        index = RandomIndex(min, max, i);
        _str += _charStr[index];
    }
    return _str;
}
// 将网络图片转换成base64格式
export function transBase64FromImage(image) {
    let canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    let ctx = canvas.getContext("2d");
    ctx.drawImage(image, 0, 0, image.width, image.height);
    // // 可选其他值 image/jpeg
    return canvas.toDataURL("image/png");
}
export function formatDate(value,args) {
    var dt = new Date(value);
    if(args == 'yyyy-M-d') {// yyyy-M-d
        let year = dt.getFullYear();
        let month = dt.getMonth() + 1;
        let date = dt.getDate();
        return `${year}-${month}-${date}`;
    } else if(args == 'yyyy-M-d H:m:s'){// yyyy-M-d H:m:s
        let year = dt.getFullYear();
        let month = dt.getMonth() + 1;
        let date = dt.getDate();
        let hour = dt.getHours();
        let minute = dt.getMinutes();
        let second = dt.getSeconds();
        return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
    } else if(args == 'yyyy-MM-dd') {// yyyy-MM-dd
        let year = dt.getFullYear();
        let month = (dt.getMonth() + 1).toString().padStart(2,'0');
        let date = dt.getDate().toString().padStart(2,'0');
        return `${year}-${month}-${date}`;
    } else {// yyyy-MM-dd HH:mm:ss
        let year = dt.getFullYear();
        let month = (dt.getMonth() + 1).toString().padStart(2,'0');
        let date = dt.getDate().toString().padStart(2,'0');
        let hour = dt.getHours().toString().padStart(2,'0');
        let minute = dt.getMinutes().toString().padStart(2,'0');
        let second = dt.getSeconds().toString().padStart(2,'0');
        return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
    }
}
export function base64toBlob(base64, type) {
    // 将base64转为Unicode规则编码
    let bstr = atob(base64, type),
        n = bstr.length,
        u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n) // 转换编码后才可以使用charCodeAt 找到Unicode编码
    }
    return new Blob([u8arr], {
        type
    })
}
export function convertHexToBase64(hexString) {
    return btoa(hexString.match(/\w{2}/g).map(char => {
        return String.fromCharCode(parseInt(char, 16))
    }).join(''))
}
export function parseRtf(rtfData) {
    if (!rtfData) {
        return []
    }
    const regexPictureHeader = /{\\pict[\s\S]+?({\\\*\\blipuid\s?[\da-fA-F]+)[\s}]*/
    const regexPicture = new RegExp('(?:(' + regexPictureHeader.source + '))([\\da-fA-F\\s]+)\\}', 'g')
    const images = rtfData.match(regexPicture)
    const result = []

    if (images) {
        for (const image of images) {
            let imageType = false
            if (image.includes('\\pngblip')) {
                imageType = 'image/png'
            } else if (image.includes('\\jpegblip')) {
                imageType = 'image/jpeg'
            }
            if (imageType) {
                result.push({
                    hex: image.replace(regexPictureHeader, '').replace(/[^\da-fA-F]/g, ''),
                    type: imageType
                })
            }
        }
    }
    return result
}
// 防抖
export function myDebounce(fun, delay = 500) {
  let timer;
  return function () {
    let ctx = this
    let args = arguments
    console.log('ctx',ctx);
    console.log('arguments',arguments);
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      timer = null
      fun.apply(ctx, args)
    }, delay)
  }
}

// 节流
export function myThrottle(fun, interval = 500) {
  let last;
  let timer;
  return function () {
      let ctx = this
      let args = arguments
      let now = new Date()
      if (last && now - last < interval) {
        clearTimeout(timer)
        timer = setTimeout(function () {
          last = now
        }, interval)
      } else {
        last = now
        fun.apply(ctx, args)
      }
  }
}
// 通用方法，创建映射
export function createMapping(array, { keyProp = 'value', valueProp = 'label' } = {}) {
  const mapping = array.reduce((acc, item) => {
    acc[item[keyProp]] = item[valueProp]
    return acc
  }, {})
  return mapping
}

//构建树结构(pid ：menu proute: route),在原来的基础上，考虑了pid为本身的情况（团队管理功能特有的情况）
export function createTreeData2(data, parentId = 'pid', children = 'children') {
    let result = []
    if (!Array.isArray(data)) {
      return result
    }
    let node = JSON.parse(JSON.stringify(data))
    node.forEach(item => delete item[children]) //已经有的话就删掉
    let map = {}
    node.forEach(item => (map[item.id] = item))
    let newNode = []
    node.forEach(dt => {
      let parents = map[dt[parentId]]
      if (dt[parentId] === dt.id) {
        newNode.push(dt)
      } else {
        parents ? (parents[children] || (parents[children] = [])).push(dt) : newNode.push(dt)
      }
    })
    return newNode
  }

export function generateUUID() {
  return 'xxxxxxxx_xxxx_4xxx_yxxx_xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0,
        v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}

// 通用下载
export function download(url, fileName) {
  fetch(url)
    .then(response => response.blob())
    .then(blob => {
      const link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = fileName || 'download';
      link.click();
      window.URL.revokeObjectURL(link.href);
    })
    .catch(error => console.error('下载文件时出错:', error));
}